package database.dao;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import model.User;

/**
 * @author Matu
 * 
 * 
 */

public class UserHibernate {

	public Boolean getUserFromDB(String username, String password) {

		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml");

		SessionFactory factory = cfg.buildSessionFactory();
		Session session = factory.openSession();

		// createQuery - HQL
		// createSQLQuery - SQL

		try {
			Query qry = session
					.createSQLQuery(
							"SELECT E.employee,UA.user_account,UA.username, P.first_name, P.last_name FROM employee E INNER JOIN user_account UA ON E.employee = UA.subject_fk "
									+ "INNER JOIN person P ON E.person_fk = P.person WHERE UA.subject_type_fk = 3  AND UA.username='"
									+ username
									+ "'  AND UA.passw=md5('"
									+ password + "')").addEntity(User.class);
		

			List l = qry.list();
//			System.out.println("Total Number Of Records : " + l.size());
			Iterator it = l.iterator();

		
			// for testing..
			while (it.hasNext()) {
				Object o = (Object) it.next();
				User p = (User) o;
				System.out.println(p.getUsername());
				System.out.println(p.getUser());

			
			
			
			}
		
			if (l.size() > 0) {
				// RETURN SO THAT HE CAN LOG ON =))
				System.out.println("you can log in :)");
				return true;

			}
		
			else {

				return false;

			}
			
		
		}
		
				
		
		
		catch (Exception e) {

			System.out
					.println("A problem with SQL statement in finding useraccount in hibernate");
			e.printStackTrace();
		}
		return null;

		
		
		
		
	
	}

}
